package com.uddenberg.wt;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Locale;

import com.uddenberg.wt.dbdefinitions.FoodMealDataDefinition.FoodMealDataColumns;
import com.uddenberg.wt.dbdefinitions.GeneralDataDefinition.GeneralDataColumns;
import com.uddenberg.wt.helpers.GeneralHelper;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioButton;

public class InsertFoodMealActivity extends Activity {

	private static final String TAG = "InsertFoodMealActivity";
	
	private Button btnGeneral;
	private RadioButton rbMeal;
	private RadioButton rbOther;
	private Button btnSave;
	
	private static TextView txtDate;
	private static TextView txtTime;
	private static RadioButton rbCaffeineYes;
	private static RadioButton rbCaffeineNo;
	private static RatingBar rbFull;
	private static RatingBar rbHealthy;
	
	private static int mHour;
    private static int mMinute;
    private static int mYear;
    private static int mMonth;
    private static int mDay;
    
    
    static final int TIME_DIALOG_ID = 0;
    static final int DATE_DIALOG_ID = 1;
    
    private Uri mUri;
    
    private static final String[] PROJECTION = new String[] {
    	GeneralDataColumns._ID, // 0
    };
	 
    // the callback received when the user "sets" the time in the dialog
    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
        new TimePickerDialog.OnTimeSetListener() {
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                mHour = hourOfDay;
                mMinute = minute;
                updateTime();
            }
        };
	
    // the callback received when the user "sets" the date in the dialog
    private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year, 
                                      int monthOfYear, int dayOfMonth) {
                    mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;
                    updateDate();
                }
            };
        
      
    
    
    
    
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.insertfood_meal_header);
        
        // If no data was given in the intent (because we were started
        // as a MAIN activity), then use our default content provider.
        Intent intent = getIntent();
        if (intent.getData() == null) {
            intent.setData(FoodMealDataColumns.CONTENT_URI);
        }
        
        mUri = intent.getData();
        
        // Perform a managed query. The Activity will handle closing and requerying the cursor
        // when needed.
        @SuppressWarnings("unused")
		Cursor cursor = managedQuery(getIntent().getData(), PROJECTION, null, null,
        		FoodMealDataColumns.DEFAULT_SORT_ORDER);
        
        
        // Set the "No" (caffeine) radio button selected as default
        rbCaffeineNo = (RadioButton)findViewById(R.id.food_meal_radio_caffeine_no);
        rbCaffeineNo.setChecked(true);
        
        
        // Handle the date and time view
        txtDate = (TextView)findViewById(R.id.food_meal_txt_date);
        txtTime = (TextView)findViewById(R.id.food_meal_txt_time);
        
        // get the current time
        final Calendar c = Calendar.getInstance();
        mHour = c.get(Calendar.HOUR_OF_DAY);
        mMinute = c.get(Calendar.MINUTE);
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        
        updateTime();
        updateDate();
        
        // Add a click listener to the time and date textview
        txtDate.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(!isFinishing()) {
					showDialog(DATE_DIALOG_ID);
				}
			}
        });
        txtTime.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(!isFinishing()) {
					showDialog(TIME_DIALOG_ID);
				}
			}
        });
        
        
        
        
        
        
        btnGeneral = (Button)findViewById(R.id.food_meal_general_insert_button);
        btnGeneral.setOnClickListener(new OnClickListener() {
    		public void onClick(View v) {
    			InsertGroupActivity.group.back();
    		}
    	});
        
        
        // Set the "Meal" radio button selected as default
        rbMeal = (RadioButton)findViewById(R.id.food_meal_radio_type_meal);
        rbMeal.setChecked(true);
        
        rbOther = (RadioButton)findViewById(R.id.food_meal_radio_type_other);
        rbOther.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(true == isChecked) {
					final Intent food_other_intent = new Intent(buttonView.getContext(), InsertFoodOtherActivity.class);
					// Create the view using InsertGroup's LocalActivityManager
					
			        View view = InsertFoodGroupActivity.group.getLocalActivityManager()  
				        .startActivity("InsertFoodOtherActivity", food_other_intent  
				        .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))  
				        .getDecorView();  
			  
			        // Again, replace the view  
			        InsertFoodGroupActivity.group.replaceView(view);  
				}
			}
		});
        
        
        btnSave = (Button)findViewById(R.id.food_meal_save);
        btnSave.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				ContentValues values = new ContentValues();
				
				
				final Calendar cal = Calendar.getInstance();
		    	cal.set(Calendar.MONTH, mMonth);
		    	cal.set(Calendar.DAY_OF_MONTH, mDay);
		    	cal.set(Calendar.YEAR, mYear);
		    	cal.set(Calendar.HOUR_OF_DAY, mHour);
		    	cal.set(Calendar.MINUTE, mMinute);
				values.put(FoodMealDataColumns.DATE, cal.getTimeInMillis()/1000);
				cal.clear();
				 
				rbCaffeineYes = (RadioButton)findViewById(R.id.food_meal_radio_caffeine_yes);
				if(rbCaffeineYes.isSelected()) {
					values.put(FoodMealDataColumns.CAFFEINE, 1);
				} else {
					values.put(FoodMealDataColumns.CAFFEINE, 0);
				}
				
				
				
				// 
				rbFull = (RatingBar)findViewById(R.id.food_meal_ratbar_full);
				values.put(FoodMealDataColumns.FULL, rbFull.getRating());
				
				// Healthyness of the food
				rbHealthy = (RatingBar)findViewById(R.id.food_meal_ratbar_healthy);
				values.put(FoodMealDataColumns.HEALTHY, rbHealthy.getRating());
				
				
				CharSequence text;
				Uri newUri = null;
				try {
					newUri = getContentResolver().insert(mUri, values);
	            } catch (Exception e) {
	            	Log.e(TAG, e.getMessage());
	            }
				if(newUri == null) {
					text = "Unable to save post";
				} else {
					text = "Saved!";
					
					// Reset all Ratbars and dates
					rbFull.setRating(0);
					rbHealthy.setRating(0);
					rbCaffeineNo.setChecked(true);
					
					mYear = c.get(Calendar.YEAR);
					mMonth = c.get(Calendar.MONTH);
					mDay = c.get(Calendar.DAY_OF_MONTH);
					mHour = c.get(Calendar.HOUR_OF_DAY);
					mMinute = c.get(Calendar.MINUTE);
					
					updateTime();
					updateDate();
					
				}
	            Context context = getApplicationContext();
	            int duration = Toast.LENGTH_LONG;

	            Toast toast = Toast.makeText(context, text, duration);
	            toast.show();
			}
		});
    }
    
    
    private static void updateTime() {
    	txtTime.setText(
	        new StringBuilder()
                .append(GeneralHelper.pad(mHour)).append(":")
                .append(GeneralHelper.pad(mMinute)));
    }
    
    private static void updateDate() {
    	final Calendar cal = Calendar.getInstance();
    	cal.set(Calendar.MONTH, mMonth);
    	cal.set(Calendar.DAY_OF_MONTH, mDay);
    	cal.set(Calendar.YEAR, mYear);
    	
    	 
    	String text = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault())
    			.format(cal.getTime());
    	txtDate.setText(text);
    }
    
    
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case TIME_DIALOG_ID:
            return new TimePickerDialog(InsertGroupActivity.group,
                    mTimeSetListener, mHour, mMinute, true);
            
        case DATE_DIALOG_ID:
            return new DatePickerDialog(InsertGroupActivity.group,
                        mDateSetListener,
                        mYear, mMonth, mDay);
        }
        
        return null;
    }
}
